package cn.learn.mq.config;

import cn.learn.mq.core.RedisMqTemplate;
import cn.learn.mq.core.pubsub.AbstractChannelMessageListener;
import cn.learn.redis.config.RedisAutoConfiguration;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;

import java.util.List;
import java.util.UUID;

/**
 * @author : 翌擎科技
 * @date : 2022/7/26 16:48
 */
@Configuration
@AutoConfigureAfter(RedisAutoConfiguration.class)
@Slf4j
public class RedisMqAutoConfiguration {
    @Bean
    public RedisMqTemplate redisMqTemplate(RedisTemplate<String, Object> redisTemplate) {
        String uuid = UUID.randomUUID().toString();
        RedisMqTemplate redisMqTemplate = new RedisMqTemplate(redisTemplate,uuid);
        // 添加拦截器
        return redisMqTemplate;
    }

    //==========消费者相关============
    @Bean
    public RedisMessageListenerContainer messageListenerContainer(RedisMqTemplate redisMqTemplate, List<AbstractChannelMessageListener<?>> listeners) {
        // 创建 RedisMessageListenerContainer 对象
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        // 设置 RedisConnection 工厂。
        container.setConnectionFactory(redisMqTemplate.getRedisTemplate().getRequiredConnectionFactory());
        // 添加监听器
        listeners.forEach(listener -> {
            listener.setRedisMqTemplate(redisMqTemplate);
            container.addMessageListener(listener, new ChannelTopic(listener.getChannel()));
            log.info("[redisMessageListenerContainer][注册 Channel({}) 对应的监听器({})]",
                    listener.getChannel(), listener.getClass().getName());
        });
        return container;
    }
}
